<template>
    <div class="BeiTie">
        <el-card class="box-card">
            <div class="header">
                <div>
                    <el-button type="primary" @click="add">新增</el-button>
                    <!-- 选择后删除 -->
                    <el-button :disabled="multipleSelection.length == 0" @click="isDelete">删除</el-button>
                </div>
                <div class="right">
                    <div class="inputs">
                        <el-input v-model="word" placeholder="请输入关键字" style="max-width: 200px;" clearable
                            @clear="getList()" />
                        <el-cascader v-model="selectvalue" :options="cateLs" :props="selfCascaderProps"
                            style="margin-left: 10px;box-sizing: border-box;" @change="handleChange" />
                    </div>
                    <div>
                        <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
                        <el-button :icon="RefreshRight" @click="resetPage">重置</el-button>
                    </div>
                </div>
            </div>
            <div class="main">
                <el-table stripe height="100%" ref="multipleTableRef" :data="tableData" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="封面图" width="120" align="center">
                        <template #default="scope">
                            <div style="margin: 5px;">
                                <el-image :preview-src-list="[scope.row.img]"
                                    style=" width: 60px; height: 60px;border-radius: 5px;" :src="scope.row.img"
                                    :zoom-rate="1.2" :initial-index="4" fit="cover" />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column property="name" label="作品名称" width="120" align="center" />
                    <el-table-column label="所属分类" show-overflow-tooltip align="center" #default="scope">
                        <span v-for="item of scope.row.type">{{ item.name }} &nbsp;&nbsp;</span>
                    </el-table-column>
                    <el-table-column label="音频">
                        <template #default="scope">
                            <div style="line-height: 30px;" v-if="scope.row.duration !== '0.00'">
                                <span style="margin: 0 10px;">{{ (scope.row.music_time/60).toFixed(2) }}</span>
                                <img src="./assets/erji.png" v-if="activeTie_id != scope.row.id"
                                    style="width:20px;height: 20px;vertical-align: -3px; cursor: pointer;" alt="" @click="playVoice(scope.row)">
                                <span v-else class="audioTag">
                                    <img style="width:20px; height: 20px;margin-right: 5px;" src="./assets/bofang.svg"
                                        alt="">
                                    <label>播放中</label>
                                </span>
                            </div>
                            <audio class="audios" ref="audios" :keyid="scope.row.id">
                                <source type="audio/mpeg" :src="scope.row.music" />
                            </audio>
                        </template>
                    </el-table-column>
                    <el-table-column label="更新时间">
                        <template #default="scope"><span style="color:#767676;font-size: 14px;">{{
                            formatDate(new Date(scope.row.newDate).getTime()) }}</span></template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="180">
                        <template #default="scope">
                            <el-button link type="primary" size="small" @click="editHandle(scope.row)">编辑</el-button>
                            <el-button link type="success" size="small" @click="showVersion(scope.row.id)">查看版本</el-button>
                            <el-button link type="danger" size="small">
                                <el-popconfirm confirm-button-text="Yes" cancel-button-text="No" :icon="InfoFilled"
                                    icon-color="#626AEF" title="确定删除吗？" @confirm="confirmEvent(scope.row)"
                                    @cancel="cancelEvent">
                                    <template #reference>
                                        <el-button link type="danger">删除</el-button>
                                    </template>
                                </el-popconfirm>
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="footer">
                <div></div>
                <el-pagination v-model:current-page="pageform.pnum" v-model:page-size="pageform.psize"
                    :page-sizes="[100, 200, 300, 400]" :small="pageform.small" :disabled="pageform.disabled"
                    :background="pageform.background" layout="prev, pager, next, jumper" :total="pageform.total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
        <!-- 添加对话框 -->
        <el-dialog v-model="form.adddialogVisible" title="新增" width="50%" :before-close="addhandleClose">
            <div>
                <el-form ref="ruleFormRef" :model="form.addform" :rules="form.rules" label-width="120px"
                    class="demo-ruleForm" status-icon>
                    <el-form-item label="图片" prop="img">
                        <el-upload class="avatar-uploader" action="/dev-api/api/uploadimg/" :show-file-list="false"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="form.addform.img" :src="form.addform.img" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="作品名称" prop="name">
                        <el-input v-model="form.addform.name" />
                    </el-form-item>
                    <el-form-item label="作品类型" prop="type">
                        <el-cascader v-model="form.addform.type" :options="cateLs" @change="addhandleChange"
                            :props="selfCascaderProps" />
                    </el-form-item>
                    <el-form-item label="音频" prop="music">
                        <el-upload class="upload-demo" drag action="/dev-api/api/uploadimg/" multiple
                            :on-success="handleAudioSuccess">
                            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                            <div class="el-upload__text">
                                支持格式：MP3、MP4
                            </div>
                        </el-upload>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="form.adddialogVisible = false">
                            取消
                        </el-button>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            保存
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
        <!-- 编辑对话框 -->
        <el-dialog v-model="form.editDialogVisible" title="编辑" width="50%" :before-close="() => {
            form.editDialogVisible = false;
        }">
            <div>
                <el-form ref="ruleFormRef" :model="form.editform" :rules="form.rules" label-width="120px"
                    class="demo-ruleForm" status-icon>
                    <el-form-item label="图片" prop="img">
                        <el-upload class="avatar-uploader" action="/dev-api/api/uploadimg/" :show-file-list="false"
                            :on-success="EdithandleAvatarSuccess">
                            <img v-if="form.editform.img" :src="form.editform.img" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="作品名称" prop="name">
                        <el-input v-model="form.editform.name" />
                    </el-form-item>
                    <el-form-item label="作品类型" prop="type">
                        <el-cascader v-model="form.editform.type" :options="cateLs" @change="edithandleChange"
                            :props="selfCascaderProps" />
                    </el-form-item>
                    <el-form-item label="音频" prop="music">
                        <el-upload class="upload-demo" drag action="/dev-api/api/uploadimg/" multiple
                            :on-success="EdithandleAudioSuccess">
                            <audio controls v-if="form.editform.music" :src="form.editform.music" />
                            <div class="el-upload__text">
                                支持格式：MP3、MP4
                            </div>
                        </el-upload>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="form.editDialogVisible = false">
                            取消
                        </el-button>
                        <el-button type="primary" @click="EditsubmitForm(ruleFormRef)">
                            保存
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
        <!-- 是否批量删除对话框-->
        <el-dialog v-model="form.delallDialogvisible" title="删除" width="30%" center>
            <span>
                您确定要删除这些数据吗？
            </span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="form.delallDialogvisible = false">取消</el-button>
                    <el-button type="primary" @click="allDelete()">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">

import { ref } from 'vue'
import { ElTable, FormInstance, UploadProps } from 'element-plus'
import { Search, RefreshRight, Plus, UploadFilled, InfoFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import request from '../../utils/request'
import timeobj from './formatTime'
import './assets/global.css'
import service from '../../utils/request'
import { number } from '@intlify/core-base'
let { formatDate, formatSeconds } = timeobj//取出方法
let router = useRouter()
let word = ref("")//模糊关键字
let selectvalue = ref([])//下拉框级联选择器
// 自定义级联选择器的配置项
let selfCascaderProps = {
    value: "id",
    label: "name",
    children: "children",
    checkStrictly: true,
    emitPath:false,
}

let activeTie_id = ref("")//播放声音显示隐藏
const tableData = ref<StoneInscription[]>([])
const cateLs = ref([])//分类名称列表
interface StoneInscription {
    id: any,
    img: string
    name: string
    type: any
    music: string
    newDate: string
    is_delete: boolean
}
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<StoneInscription[]>([])//多选后的数组
const handleSelectionChange = (val: StoneInscription[]) => {
    multipleSelection.value = val;
}
// 获取数据列表
let getList = async () => {
    let data: any = await request.get(`/api/tabletworks/tabletWorksList/${word.value == "" ? " " : word.value}/${pageform.pnum}?id=${selectvalue.value}`)
    // total还没赋值呢
    pageform.total = data.total
    tableData.value = [...data.data]
}
// 获取分类数组
let getCatels = async () => {
    let { data } = await service.get(`/api/classify/classfiy/`)
    cateLs.value = data
}
//分页选项
let pageform = reactive({
    psize: 10,
    pnum: 1,
    small: true,
    background: true,
    disabled: false,
    total: 0
})
// 表单校验类型
const ruleFormRef = ref<FormInstance>()
// 表单配置
let form:any = reactive({
    adddialogVisible: false,
    editDialogVisible: false,
    delallDialogvisible: false,
    addform: { name: "", img: "", type: "", music: "" },
    editform: {
        id:"",
        music: "",
        img: "",
        name: "",
        type: "",
        music_time:0,
    },
    rules: {
        name: [
            { required: true, message: '请输入作品名称', trigger: 'blur' },
            { min: 3, max: 25, message: '长度是3-25', trigger: 'blur' },
        ],
        img: [
            { required: true, message: '请上传图片信息', trigger: 'blur' },
        ],
        type: [
            {
                required: true,
                message: '请选择作品类型',
                trigger: 'change',
            },
        ],
        music: [
            { required: true, message: '请上传音频资源', trigger: 'blur' },
        ]
    },
    audioform: {
        music_time: 0,
        id: "",
    }

})
// 编辑碑帖
let editHandle =async (row: any) => {
    // 通过id获取单个碑帖
    form.editform.id=row.id
    form.editDialogVisible = true
    let {data} = await request(`/api/tabletworks/TabletWorkBeforUpd?id=${row.id}`)    
    form.editform.type=data.type[0].id
    form.editform.name=data.name
    form.editform.img=data.img
    form.editform.music=data.music
    form.editform.music_time=data.music_time
}
// 关闭对话框
let addhandleClose = () => { form.adddialogVisible = false; form.editDialogVisible = false }
let add = () => { form.adddialogVisible = true }
//添加中的 级联选择器
const addhandleChange = (value: any) => {
    form.addform.type = value
}
// 选中查询
const handleChange = (value: any) => {
    selectvalue.value = value
}
// 编辑分类
const edithandleChange = (value: any) => {
    form.editform.type = value
}
// 添加确定
const submitForm = async (formEl: FormInstance | undefined) => {
    let a: any = []
    if (form.addform.type.length == 1) {
        a.push(form.addform.type[0])
    }else if(typeof(form.addform.type)!=='object'){
        a.push(form.addform.type)
    }
     else {
        a.push(form.addform.type[form.addform.type.length - 1])
    }
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            let data: any = await request.post(`/api/tabletworks/tabletWorksAdd`, {
                name: form.addform.name,
                type: a,
                img: form.addform.img,
                music: form.addform.music
            })
            ElMessage.info(data.msg)
            editAudioTime(data.data.id)
            getList()
            form.adddialogVisible = false
            form.addform = {}
        } else {
            ElMessage.error("请完善创建作品信息")
        }
    })
}
// 修改音频时长函数
let editAudioTime = async (id: any) => {
    let data = await request.put(`/api/tabletworks/tabletWorksUpd/${id}`, {
        "music_time": form.audioform.music_time||form.editform.music_time
    })
}
// 编辑
const EditsubmitForm = async (formEl: FormInstance | undefined) => {
    let a: any = []
    if (form.editform.type.length == 1) {
        a.push(form.editform.type[0])
    }else if(typeof(form.editform.type)!=='object'){
        a.push(form.editform.type)
    } 
    else {
        a.push(form.editform.type[form.editform.type.length - 1])
    }
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            if (form.editform.type.length == 0) return ElMessage("分类不能为空")
            let data:any = await request.put(`/api/tabletworks/tabletWorksUpd/${form.editform.id}`, {
                name: form.editform.name,
                type: a,
                img: form.editform.img,
                music: form.editform.music
            })
            ElMessage.info(data.msg)
            form.editDialogVisible = false;
            getList()
        } else {
            ElMessage.info("编辑作品信息请完善")
        }
    })
}

//全部删除功能
let isDelete = async () => { form.delallDialogvisible = true }
// 全部删除确定
let allDelete = async () => {
    let val = []
    for (const item of multipleSelection.value) {
        val.push({ id: item.id, is_delete: 1 })
    }
    let data: any = await request.post(`/api/tabletworks/TabletWorksDelAll`, val)
    ElMessage.info(data.msg)
    form.delallDialogvisible = false;
    getList()
}
// 气泡删除框
const confirmEvent = async (row: any) => {
    let data: any = await request.delete(`/api/tabletworks/tabletWorksUpd/${row.id}?is_delete=${1}`)
    ElMessage.info(data.msg)
    getList()
    form.adddialogVisible = false
}
const cancelEvent = () => { }
//添加文件上传的函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    // form.addform.img = URL.createObjectURL(uploadFile.raw!)
    form.addform.img = response.path
}
// 计算音频的时长
const countAudioTime = async (audio: any) => {
    while (isNaN(audio.duration) || audio.duration === Infinity) {
        // 延迟一会 不然网页都卡死
        await new Promise(resolve => setTimeout(resolve, 200));
        // 设置随机播放时间，模拟调进度条
        audio.currentTime = 10000000 * Math.random();
    }
    return audio.duration
}
// 添加上传录音
const handleAudioSuccess: UploadProps['onSuccess'] = async (
    response,
    uploadFile
) => {
    form.addform.music = response.path
    const musics = new Audio()
    musics.src = response.path
    let duration = await countAudioTime(musics)
    form.audioform.music_time = duration//拿到上传的音频时长
    // 这里能拿到时长
}
//编辑图片上传钩子函数
const EdithandleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    // form.addform.img = URL.createObjectURL(uploadFile.raw!)
    form.editform.img = response.path
}
//编辑录音上传钩子函数
const EdithandleAudioSuccess: UploadProps['onSuccess'] =async (
    response,
    uploadFile
) => {
    // form.addform.img = URL.createObjectURL(uploadFile.raw!)
    form.editform.music = response.path
    const musics = new Audio()
    musics.src = response.path
    let duration = await countAudioTime(musics)
    form.editform.music_time = duration//拿到上传的音频时长    
    editAudioTime(form.editform.id)
}
// 文件上传前生命钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}
//分页监听函数
let handleSizeChange = (val: number) => {
    pageform.psize = val
    getList()
}
//分页监听函数
let handleCurrentChange = (val: number) => {
    pageform.pnum = val
    getList()
}
let audios: any = ref(null)
//播放声音
let playVoice = async (row: any) => {
    let { music, id } = row
    activeTie_id.value = id
    audios.value.src = music
    audios.value.play()
}
// 查看版本跳转到查看版本
let showVersion = (id: any) => {
    // 版本页面根据 id 来查看 当前的碑帖的 所有版本信息
    router.push(`/stoneInscription/versions?id=${id}`)
}
// 重置页面操作
let resetPage = () => {
    getList()
    word.value = ""
    selectvalue.value = []
}
onMounted(() => {
    getList()
    getCatels()

})



</script>

<style lang="scss" scoped>
.BeiTie {
    width: 100%;
    height: 100%;
    min-width: 950px;
}

:deep(.el-table__row) {
    text-align: center !important;
    color: #737373;
    font-size: 15px;
}

// 表头行高背景
:deep(.el-table__header) {
    line-height: 50px;
    background-color: #f2f2f2;
    // border: 1px solid #eaeaea;
    font-size: 15px;
    font-weight: 500;
}

// 表项border
:deep(.el-table__row) {
    border: 1px solid #eaeaea;
    border-collapse: collapse;
}

// 表项 斑马色
:deep(.el-table__row:nth-child(even)) {
    background-color: #f5f5f5;
}

// 播放激活
// 解决image 全局蒙版权重的问题
:deep(.el-table .el-table__cell) {
    z-index: auto !important;
}

.audioTag {
    width: 80px;
    font-size: 13px;
    height: 30px;
    border: #409eff 2px solid;
    border-radius: 12px;
    display: flex;
    display: inline-block;
    line-height: 30px;
    align-items: center;

    img {
        vertical-align: middle;
    }
}
</style>

<!-- // 上传文件样式 -->
<style>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>